package club.itstudio.itouc.core.util

import java.awt.image.BufferedImage
import java.io.File
import java.io.IOException
import javax.imageio.ImageIO

/**
 * 图片识别工具
 */

object Ocr {

    /**
     * 裁剪图片：去掉黑边
     */
    private fun clipImage(srcImage: BufferedImage): BufferedImage {
        return srcImage.getSubimage(1, 1, srcImage.width - 2, srcImage.height - 2)
    }

    /**
     * 灰度化
     */
    private fun grayImage(srcImage: BufferedImage): BufferedImage {
        return copyImage(srcImage, BufferedImage(srcImage.width, srcImage.height, BufferedImage.TYPE_BYTE_GRAY))
    }

    /**
     * 二值化
     */
    private fun binaryImage(srcImage: BufferedImage): BufferedImage {
        return copyImage(srcImage, BufferedImage(srcImage.width, srcImage.height, BufferedImage.TYPE_BYTE_BINARY))
    }

    private fun copyImage(srcImage: BufferedImage, destImage: BufferedImage): BufferedImage {
        for (y in 0 until srcImage.height) {
            for (x in 0 until srcImage.width) {
                destImage.setRGB(x, y, srcImage.getRGB(x, y))
            }
        }
        return destImage
    }

    fun imageProcess(srcPath: String, desPath: String) {
        try {
            val originImage = ImageIO.read(File(srcPath))
            val processedImage = binaryImage(grayImage(clipImage(originImage)))
            ImageIO.write(processedImage, "JPEG", File(desPath))
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }

}